//
//  MCChangeStoreViewController.swift
//  StoreManage
//
//  Created by MC on 2018/1/31.
//  Copyright © 2018年 MC. All rights reserved.
//

import UIKit

class MCChangeStoreViewController: MCViewController {

    var userDict : [String:Any] = [:] {
        didSet {
            let userId = userDict["userId"] as? NSNumber ?? 0
            let userName = userDict["userName"] as? String ?? ""
            let token = userDict["token"] as? String ?? ""

            UserDefaults.LoginInfo.set(value: userId.stringValue, forKey: .userId)

            UserDefaults.LoginInfo.set(value: userName, forKey: .userName)
            UserDefaults.LoginInfo.set(value: token, forKey: .token)
            // 给极光设置别名和标签
            JPUSHService.setAlias(userId.stringValue, completion: nil, seq: 0)
        }
    }
    
    
    var isLoginVCJump = false
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        baseSetting()
        
        initUI()
        
        sendNetworking()
    }
    
    // MARK: - System Delegate
    
    // MARK: - Custom Delegate
    
    // MARK: - Action
    
    // MARK: - Network
    func sendNetworking() {
        let para = [
            "baUserId" : MCUserinfo_getUserId(),
            ] as [String : Any]
        
        MCNetwork_post(url: JAVA_storeSelect, para: para as [String : AnyObject], vc: self,hudSuperView: self.view,isHiddenTabbar: true, success: { (response) in
            let dataAarry = response["data"] as? NSArray ?? []
            for dict in dataAarry {
                let tempDict = dict as? [String:Any] ?? [:]
                let model = MCChangeStoreModel()
                model.setValuesForKeys(tempDict)
                self.dataArrayM.add(model)
            }
            
            if self.dataArrayM.count == 1 {
                if self.isLoginVCJump {   // 进入首页
                    let model = self.dataArrayM[0] as! MCChangeStoreModel

                    let logoPath = model.logoPath
                    let storeName = model.storeName
                    let storeId = model.storeId
                    let isBill = model.isBill
                    let levelTuples = MCLevelConversion(level: model.level)
                    let nickName = model.nickName
                    let picture = model.picture
                    
                    
                    
                    UserDefaults.LoginInfo.set(value: isBill, forKey: .isBill)
                    UserDefaults.LoginInfo.set(value: storeName, forKey: .storeName)
                    UserDefaults.LoginInfo.set(value: logoPath, forKey: .logoPath)
                    UserDefaults.LoginInfo.set(value: String(storeId), forKey: .storeId)
                    UserDefaults.LoginInfo.set(value: String(levelTuples.level), forKey: .level)
                    UserDefaults.LoginInfo.set(value: levelTuples.levelName, forKey: .levelName)
                    UserDefaults.LoginInfo.set(value: nickName, forKey: .nickName)
                    UserDefaults.LoginInfo.set(value: picture, forKey: .picture)

                    // 给极光设置标签
                    JPUSHService.setTags([String(storeId)], completion: nil, seq: 0)
                    
                    let tabbarC = MCTabBarController()
                    self.present(tabbarC, animated: false, completion: nil)
                }
            }
            
            
            self.tableView.reloadData()
            
        }, dislike: { (response) in }) { (error) in }
    }
    
    // MARK: - Method
    func baseSetting() {
        self.title = "选择店铺"
        self.view.backgroundColor = UIColor.white

        if isLoginVCJump {
            let view = UIView()
            view.frame = CGRect.init(x: 0, y: 0, width: 20, height: 20)
            view.backgroundColor = UIColor.white
            navigationItem.leftBarButtonItem = UIBarButtonItem.init(customView: view)
        }
    }
    
    func initUI() {
        view.addSubview(tableView)
        tableView.snp.remakeConstraints { (make) ->Void in
            make.edges.equalTo(view)
        }
    }
    
    // MARK: - Setter & Getter
    lazy private var tableView: MCTableView = {
        let tableView = MCTableView.init(frame: CGRect.zero, style: UITableViewStyle.plain)
        tableView.delegate = self
        tableView.dataSource = self
        return tableView
    }()
    
    lazy var dataArrayM: NSMutableArray = {
        let arrayM = NSMutableArray()
        return arrayM
    }()
}

extension MCChangeStoreViewController : UITableViewDelegate,UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataArrayM.count
    }
    
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 100
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = MCChangeStoreCell.init(style: UITableViewCellStyle.value1, reuseIdentifier: "cell")
        cell.selectionStyle = UITableViewCellSelectionStyle.none
        
        cell.model = self.dataArrayM[indexPath.row] as! MCChangeStoreModel
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model = self.dataArrayM[indexPath.row] as! MCChangeStoreModel
        // 存储用户信息
        let logoPath = model.logoPath
        let storeName = model.storeName
        let storeId = model.storeId
        let isBill = model.isBill
        
        let levelTuples = MCLevelConversion(level: model.level)
        
        
        UserDefaults.LoginInfo.set(value: storeName, forKey: .storeName)
        UserDefaults.LoginInfo.set(value: logoPath, forKey: .logoPath)
        UserDefaults.LoginInfo.set(value: String(storeId), forKey: .storeId)
        UserDefaults.LoginInfo.set(value: String(isBill), forKey: .isBill)
        UserDefaults.LoginInfo.set(value: String(levelTuples.level), forKey: .level)
        UserDefaults.LoginInfo.set(value: levelTuples.levelName, forKey: .levelName)

    
        tableView.reloadData()
        
        // 给极光设置标签
        JPUSHService.setTags([String(storeId)], completion: nil, seq: 0)
        
        if isLoginVCJump {   // 进入首页
            let tabbarC = MCTabBarController()
            self.present(tabbarC, animated: false, completion: nil)
        } else {     // 返回到首页
            MCHUD_text(message: "正在切换店铺...", view: self.view, delay: 1.2)
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.2, execute: {
                MCNotification_post(name: NOTIFICATION_ChangeStore, object: nil)
                for i in 0..<(self.navigationController?.viewControllers.count)! {
                    
                    if self.navigationController?.viewControllers[i].isKind(of: MCHomePageViewController.self) == true {
                        
                        _ = self.navigationController?.popToViewController(self.navigationController?.viewControllers[i] as! MCHomePageViewController, animated: true)
                        break
                    }
                }

                
            })
        }
    }
}

